
import { Image, RichText, Text, View } from '@tarojs/components';
import { eventCenter, getCurrentInstance } from '@tarojs/runtime';
import Taro from "@tarojs/taro";
import { useEffect, useState } from 'react';
import { globalHost } from '../../util/data';
import { sendPost } from '../../../utils/http';
import { WorkItem } from '../work-detail/msg';
import './item.less';
import { isTaskException, PaintMessage, TaskStatus } from './msg';

const host = globalHost
const loadingImg = require('../../assert/Paint_Icon_Loading.png')
const placeholderImg = require('../../assert/placeholder.png')
const timeoutValue = 2 * 60 // 秒

const PaintItem = (props: {
    id: string, item: PaintMessage,
    btnU: (item: PaintMessage, idx: number) => void,
    btnV: (item: PaintMessage, idx: number) => void,
    onTimeout: () => void
}) => {

    const { id, item, btnU, btnV, onTimeout } = props
    const [isImgLoading, setIsImgLoading] = useState(false);


    const onShow = () => {
        // console.log('on item show...');
    }

    const timeoutHandle = () => {
        if (item.type === 'robot' && item.status !== 1200) {
            item.status = -1
            item.content = '官方生图超时'
            onTimeout && onTimeout()
        }
    }

    useEffect(() => {
        const onShowEventId = getCurrentInstance().router?.onShow
        eventCenter.on(onShowEventId ? onShowEventId : "空ID", onShow, this)

        /* 要分别处理不同状态
        1、一开始就无效，如敏感词或其他异常导致，此时任务状态始终是初始态或者服务端返回了异常。【直接按失败处理，这种情况不会保存到本地】
        2、接收到更新，此时状态会变为1001，但是没有收到最终的成功。【补偿机制】
        */

        if (item.type !== 'robot') { // 非图片的不处理
            return
        }

        if (isTaskException(item.status)) {
            console.log('item异常不处理...');
            return
        }

        if (item.status === TaskStatus.PROCESSIN) {
            // 通过创建时间，计算应该超时的时间
            let createDate = new Date(item.createTime)
            createDate.setSeconds(createDate.getSeconds() + timeoutValue)
            let offetSeconds = Math.floor((createDate.getTime() - new Date().getTime()) / 1000)
            console.log('目标超时时间：', createDate, `还剩${offetSeconds}s`)
            if (offetSeconds > 0) {
                // 继续等待服务器返回，直到超时
                setTimeout(timeoutHandle, offetSeconds * 1000)
            } else {
                // 直接查询修正，但是有可能服务器也还没完成，此时不管服务器了，直接按异常处理
                // 此时会放开”加载中操作阻拦“，用户可能创建新的作品，此时如果服务器旧的消息更新状态，需要通过taskId比对抛弃
                item.status = -1
                item.content = '官方生图超时'
                onTimeout && onTimeout()
            }
            return
        }

        if (item.status === TaskStatus.FINISH) {
            if (item.imageProgess < 100) { // 历史异常任务，丢失最后一个推送
                console.log(`任务异常${item.imageProgess}，自动检测任务实际结果`)
                sendPost(host + '/ai/work/query', { 'taskId': item.taskId }, {
                    success: (res) => {
                        if (res.data.code !== -1) {
                            let workItem = res.data.data as WorkItem
                            console.log('作品查询结果:', workItem)
                            item.image = workItem.imageUrl
                            item.imageProgess = 100
                        }
                    }
                })
            }
        }
    }, [])

    const handleWorkClick = (item: PaintMessage) => {
        let workItem: WorkItem = {
            id: 0,
            prompt: item.prompt,
            taskId: item.taskId,
            uIndex: item.imageType,
            status: item.status,
            imageUrl: item.image,
            createTime: item.createTime,
        }
        Taro.navigateTo({
            url: `/pages/common/work-detail/index?workItem=${encodeURIComponent(JSON.stringify(workItem))}&imageType=${item.imageType}`,
        })
    }

    return (
        <View id={id} className='paint-item-wrapper' >
            <View className='paint-item-top'>
                <View style={{ fontSize: '14px', color: '#f0e877' }}>绘画助理</View>
                <Text style={{ fontSize: '8px', marginLeft: '10px', color: 'white', backgroundColor: '#762fc8', borderRadius: '20px', padding: '2px 5px' }}>幻景画师</Text>
                <Text style={{ fontSize: '14px', marginLeft: '10px', color: 'white', visibility: item.type === 'robot' ? 'visible' : 'hidden' }}>({item.imageProgess}%)</Text>
                {/* <Text style={{ fontSize: '8px', color: '#8e9294' }}>{item.createTime?.toString()}</Text> */}
                <Text style={{ fontSize: '8px', color: '#8e9294' }}>{item.createTime}</Text>
            </View>
            <View className='paint-item-content'>
                <RichText nodes={item.prompt} style={{ fontSize: '14px', color: 'white', width: '100%' }} />
                {/* 渲染图片 */}
                {item.image.startsWith('http') && item.type === 'robot' && (
                    <Image className='img-self' src={item.image} mode='widthFix' lazyLoad onLoad={() => setIsImgLoading(true)}
                        onClick={() => handleWorkClick(item)} />
                )}
                {item.status > 0 && !item.image.startsWith('http') && item.type === 'robot' && (
                    <View className='img-loading-container'>
                        <Image src={loadingImg} mode="aspectFill" style={{ width: '20px', height: '20px', animation: 'rotate 3s linear infinite' }} />
                    </View>
                )}
                {item.status < 0 && !item.image.startsWith('http') && item.type === 'robot' && (
                    <View className='img-loading-container'>
                        <Image src={placeholderImg} mode="aspectFill" style={{ width: '60px', height: '60px', opacity: 0.5 }} />
                    </View>
                )}
                {/* 渲染操作按钮 */}
                {item.image.startsWith('http') && item.imageType === 0 && item.imageProgess >= 98 && isImgLoading && (
                    <View style={{ display: 'flex', width: '100%', margin: '0px 0', alignItems: 'flex-start', justifyContent: '', flexDirection: 'column' }}>
                        <View style={{ display: 'flex', width: '100%', margin: '5px 0', alignItems: 'center', justifyContent: 'space-between' }}>
                            <View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 1)} >左上放大</Text></View>
                            <View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 2)} >右上放大</Text></View>
                            <View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 3)} >左下放大</Text></View>
                            <View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => btnU(item, 4)} >右下放大</Text></View>
                        </View>
                        {/* <View style={{ display: 'flex', width: '100%', margin: '0px 0', alignItems: 'center', justifyContent: 'space-between' }}>
                            <View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnV(item, 1)} >左上相似</Text></View>
                            <View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnV(item, 2)} >右上相似</Text></View>
                            <View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnV(item, 3)} >左下相似</Text></View>
                            <View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => btnV(item, 4)} >右下相似</Text></View>
                        </View> */}
                    </View>
                )}
            </View>
        </View>
    )
}

export default PaintItem;